﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Visiblox.Charts;
using System.Data;
using System.Linq;

namespace TARADesktopPatient
{
	public partial class MainPage
	{
        tara_wcf.ItaraServiceClient svc = new tara_wcf.ItaraServiceClient();
        List<tara_wcf.EXE> exeList = new List<tara_wcf.EXE>();
        int workCount = 0;
        public static List<KeyValuePair<int, int>> jointList = new List<KeyValuePair<int, int>>();
        public static List<tara_wcf.gamePlay> gpList = new List<tara_wcf.gamePlay>();
        public static int patientID;
		public MainPage(tara_wcf.patient p)
		{
			this.InitializeComponent();

            jointList = p.JointSeverity;
            patientID = p.Uid;
            lblUsername.Text = p.FirstName + " " + p.LastName;
            svc.retrieveGameAssignedtoPatientCompleted += new EventHandler<tara_wcf.retrieveGameAssignedtoPatientCompletedEventArgs>(svc_retrieveGameAssignedtoPatientCompleted);
            svc.retrieveGameAssignedtoPatientAsync(p.Uid);
            svc.getMaxMinAngleCompleted += new EventHandler<tara_wcf.getMaxMinAngleCompletedEventArgs>(svc_getMaxMinAngleCompleted);
            svc.getMaxMinAngleAsync(p.Uid);
            svc.retrieveSessionOfPatientCompleted += new EventHandler<tara_wcf.retrieveSessionOfPatientCompletedEventArgs>(svc_retrieveSessionOfPatientCompleted);
            //test data
            # region add color into list
            //colurList.Add(Colors.Red);
            //colurList.Add(Colors.Gold);
            colurList.Add(Colors.DeepPink);
            colurList.Add(Colors.Black);
            colurList.Add(Colors.Brown);
            colurList.Add(Colors.DarkBlue);
            colurList.Add(Colors.Crimson);
            //colurList.Add(Colors.SpringGreen);
            colurList.Add(Colors.DarkCyan);
            colurList.Add(Colors.DarkGreen);
            colurList.Add(Colors.DarkMagenta);
            colurList.Add(Colors.DarkOrange);
            colurList.Add(Colors.DarkViolet);
            colurList.Add(Colors.SandyBrown);
            colurList.Add(Colors.Salmon);
            colurList.Add(Colors.SlateGray);
            colurList.Add(Colors.SkyBlue);
            colurList.Add(Colors.RoyalBlue);
            colurList.Add(Colors.Purple);
            colurList.Add(Colors.Plum);
            colurList.Add(Colors.Pink);
            colurList.Add(Colors.PeachPuff);
            colurList.Add(Colors.PaleVioletRed);
            colurList.Add(Colors.PaleGoldenrod);
            colurList.Add(Colors.Orchid);

            colurList.Add(Colors.MediumTurquoise);
            colurList.Add(Colors.Maroon);
            colurList.Add(Colors.LimeGreen);
            colurList.Add(Colors.LightYellow);
            colurList.Add(Colors.Green);
            colurList.Add(Colors.BurlyWood);
            colurList.Add(Colors.Coral);
            colurList.Add(Colors.DarkRed);
            colurList.Add(Colors.DarkSeaGreen);
            colurList.Add(Colors.DarkTurquoise);
            colurList.Add(Colors.ForestGreen);

            colurList.Add(Colors.MediumTurquoise);
            colurList.Add(Colors.Maroon);
            colurList.Add(Colors.LimeGreen);
            colurList.Add(Colors.LightYellow);
            colurList.Add(Colors.Green);
            colurList.Add(Colors.BurlyWood);
            colurList.Add(Colors.Coral);
            colurList.Add(Colors.DarkRed);
            colurList.Add(Colors.DarkSeaGreen);
            colurList.Add(Colors.DarkTurquoise);
            colurList.Add(Colors.ForestGreen);

            # endregion
            //svc.retrieveAllEXECompleted += new EventHandler<tara_wcf.retrieveAllEXECompletedEventArgs>(svc_retrieveAllEXECompleted);
            svc.retrieveAllEXECompleted += new EventHandler<tara_wcf.retrieveAllEXECompletedEventArgs>(svc_retrieveAllEXECompleted);
            
            // Insert code required on object creation below this point.
		}

        void svc_retrieveSessionOfPatientCompleted(object sender, tara_wcf.retrieveSessionOfPatientCompletedEventArgs e)
        {
            workCount++;

            if (e.Error == null && e.Result != null)
            {
                patientSessionList = e.Result;
            }

        }

        void svc_retrieveAllEXECompleted(object sender, tara_wcf.retrieveAllEXECompletedEventArgs e)
        {
            workCount++;

            if (e.Error == null && e.Result != null)
            {
                listOfEXEAvailable = e.Result;
                cbxTreatment.Items.Clear();
                foreach (tara_wcf.EXE exe in listOfEXEAvailable)
                {
                    ComboBoxItem item = new ComboBoxItem();
                    item.Tag = exe.Uid;
                    item.Content = exe.Name;
                    cbxTreatment.Items.Add(item);
                }
            }
        }

        void svc_getMaxMinAngleCompleted(object sender, tara_wcf.getMaxMinAngleCompletedEventArgs e)
        {
            if (e.Error == null && e.Result != null)
            {
                gpList = e.Result;
            }
        }

        void svc_retrieveGameAssignedtoPatientCompleted(object sender, tara_wcf.retrieveGameAssignedtoPatientCompletedEventArgs e)
        {
            if (e.Error == null && e.Result != null)
            {
                exeList = e.Result;
                treatmentPanel.Children.Clear();
                foreach (tara_wcf.EXE x in exeList)
                {
                    //TreatmentItem ti = new TreatmentItem(x);
                    //ti.lblDescription.Text = x.Description;
                    //ti.lblName.Text = x.Name;
                    treatmentPanel.Children.Add(new TreatmentItem(x));
                }
            }
        }

        #region treatment tabs
        private void ChooseTab(string tabName, string tabGroupName)
        {
            foreach (UIElement element in Tabs.Children)
            {
                if (element is Border)
                {
                    Border tab = (Border)element;
                    tab.Background = new SolidColorBrush(Color.FromArgb(255, 13, 122, 192));
                }
            }

            foreach (UIElement element in TabGroups.Children)
            {
                if (element is Grid)
                {
                    element.Visibility = Visibility.Collapsed;
                }    
            }

            foreach (UIElement element in Tabs.Children)
            {
                if (element is Border)
                {
                    Border tab = (Border)element;
                    if (tab.Name.Equals(tabName))
                    {
                        tab.Background = new SolidColorBrush(Color.FromArgb(255, 118, 176, 255));
                        break;
                    }
                }              
            }

            foreach (UIElement element in TabGroups.Children)
            {
                if (element is Grid)
                {
                    Grid tabGroup = (Grid)element;
                    if (tabGroup.Name.Equals(tabGroupName))
                    {
                        tabGroup.Visibility = Visibility.Visible;
                    }
                }                
            }
        }

        private void tabMyProgress_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ChooseTab("tabMyProgress", "MyProgress");
        }

        private void tabMyTreatments_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ChooseTab("tabMyTreatments", "MyTreatments");
        }
        #endregion

        private void btnLogout_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new LoginPage());
        }

        #region graph
        List<Color> colurList = new List<Color>();
        int selectedID = 0;
        List<tara_wcf.session> patientSessionList;
        List<tara_wcf.EXE> listOfEXEAvailable;
        List<string> gameKeyList = new List<string>();
        //jointList contains impairment joints
        private void cbxTreatment_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            ComboBox comboxBox = (ComboBox)sender;
            if (comboxBox.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)comboxBox.SelectedItem;
                selectedID = Convert.ToInt16(item.Tag);

                List<CheckBox> comboBoxItemList = new List<CheckBox>();
                gameKeyList.Clear();

                sp_Attribute.Visibility = Visibility.Visible;
                try
                {
                    foreach (tara_wcf.session patientSession in patientSessionList)
                    {
                        if (patientSession.ExeID == selectedID)
                        {
                            List<tara_wcf.gamePlay> patientGamePlayList = new List<tara_wcf.gamePlay>();
                            patientGamePlayList = patientSession.GamePlaylist;

                            foreach (tara_wcf.gamePlay gameplay in patientGamePlayList)
                            {
                                if (gameplay.GameKey.Contains("Angle X"))
                                {
                                    gameKeyList.Add("Range X");
                                }
                                else if (gameplay.GameKey.Contains("Angle Y"))
                                {
                                    gameKeyList.Add("Range Y");
                                }
                                else if (gameplay.GameKey.Contains("Angle Z"))
                                {
                                    gameKeyList.Add("Range Z");
                                }
                                else
                                    gameKeyList.Add(gameplay.GameKey);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                }

                gameKeyList = gameKeyList.Distinct().ToList();

                cbxYAxis.SelectedIndex = -1;
                cbxYAxis.ItemsSource = null;
                cbxYAxis.Items.Clear();
                comboBoxItemList.Clear();

                foreach (string gameKey in gameKeyList)
                {
                    CheckBox cbx = new CheckBox();
                    cbx.Checked += new RoutedEventHandler(cbx_Checked);
                    cbx.Unchecked += new RoutedEventHandler(cbx_Unchecked);
                    cbx.Content = gameKey;
                    comboBoxItemList.Add(cbx);
                }
                cbxYAxis.ItemsSource = comboBoxItemList;
            }
        }

        void cbx_Unchecked(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            createChart();
        }

        void cbx_Checked(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            createChart();
        }

        private void cbxPerformance_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // TODO: Add event handler implementation here.
        }

        private void cbxYAxis_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // TODO: Add event handler implementation here.
        }

        int colorCount = 0;
        bool gotRange = false;
        private void createChart()
        {
            gotRange = false;
            colorCount = 0;
            progressChart.Series.Clear();
            Visiblox.Charts.DateTimeAxis dateTimeaxis = new DateTimeAxis();
            progressChart.XAxis = dateTimeaxis;
            List<string> selectedXYZ = new List<string>();
            List<string> selectedKeyList = new List<string>();

            #region check for selected items

            foreach (CheckBox cbx in cbxYAxis.Items)
            {
                if (cbx.IsChecked == true)
                {
                    if (!cbx.Content.ToString().Contains("Range"))
                    {
                        selectedKeyList.Add(cbx.Content.ToString());
                    }
                    else
                    {
                        gotRange = true;
                        if (cbx.Content.ToString().Contains("X"))
                        {
                            selectedXYZ.Add("X");
                        }
                        else if (cbx.Content.ToString().Contains("Y"))
                        {
                            selectedXYZ.Add("Y");
                        }
                        else if (cbx.Content.ToString().Contains("Z"))
                        {
                            selectedXYZ.Add("Z");
                        }

                    }
                }
            }
            #endregion

            if (gotRange == false)
            {
                #region noRange
                int keyCount = 0;

                for (int i1 = 0; i1 < selectedKeyList.Count; i1++)
                {
                    string gameKey = selectedKeyList[i1];
                    int count = 0;

                    DataSeries<DateTime, double> temp = new DataSeries<DateTime, double>(gameKey);
                    int xCount = 0;
                    foreach (tara_wcf.session ps in patientSessionList)
                    {
                        if (ps.ExeID == selectedID)
                        {
                            List<tara_wcf.gamePlay> patientGamePlayList = new List<tara_wcf.gamePlay>();
                            patientGamePlayList = ps.GamePlaylist;

                            List<int> gameplayIDlist = new List<int>();

                            foreach (tara_wcf.gamePlay gameplay in patientGamePlayList)
                            {
                                if (!gameplayIDlist.Contains(gameplay.Uid))
                                {
                                    if (gameKey.Equals(gameplay.GameKey))
                                    {
                                        xCount++;
                                        gameplayIDlist.Add(gameplay.Uid);
                                    }
                                    //if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                                    //if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || gameplay.StageName.Equals("nostage")))
                                    //{
                                    //}

                                }
                            }
                        }
                    }

                    DateTime[] x = new DateTime[xCount];
                    double[] y = new double[xCount];

                    foreach (tara_wcf.session patientSession in patientSessionList)
                    {
                        if (patientSession.ExeID == selectedID)
                        {
                            List<tara_wcf.gamePlay> patientGamePlayList = new List<tara_wcf.gamePlay>();
                            patientGamePlayList = patientSession.GamePlaylist;

                            List<int> gameplayIDlist = new List<int>();

                            foreach (tara_wcf.gamePlay gameplay in patientGamePlayList)
                            {
                                if (!gameplayIDlist.Contains(gameplay.Uid))
                                {
                                    //if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                                    //{
                                    if (gameKey.Equals(gameplay.GameKey))
                                    {
                                        gameplayIDlist.Add(gameplay.Uid);
                                        x[count] = patientSession.Dateofplay;
                                        y[count] = Convert.ToDouble(gameplay.GameValue);
                                        count++;
                                    }
                                    //}
                                }
                            }
                        }
                        keyCount++;
                    }
                    for (int i = 0; i < x.Length; i++)
                    {
                        temp.Add(new DataPoint<DateTime, double>() { X = x[i], Y = y[i] });
                    }
                    LineSeries ls = new LineSeries();

                    SolidColorBrush color1 = new SolidColorBrush();
                    color1.Color = colurList[colorCount];
                    ls.LineStroke = color1;
                    colorCount++;
                    ls.LineStrokeThickness = 4;

                    progressChart.Series.Add(ls);


                    progressChart.Series[i1].DataSeries = temp;
                }

                #endregion
            }
            else
            {
                #region gotRange

                DateTime[] xx = new DateTime[2];
                double[] yy = new double[2];
                double gameValue1 = 0.0;
                double gameValue2 = 0.0;

                List<int> jointAvailable = new List<int>();
                bool showLegendRange = false;

                List<KeyValuePair<KeyValuePair<int, string>, Color>> jointColorAssignList = new List<KeyValuePair<KeyValuePair<int, string>, Color>>();



                foreach (tara_wcf.session patientSession in patientSessionList)
                {
                    DataSeries<DateTime, double> temp = new DataSeries<DateTime, double>("Range");
                    //DateTime[] x = new DateTime[2];
                    //double[] y = new double[2];
                    //double gameValue1 = 0.0;
                    //double gameValue2 = 0.0;
                    if (patientSession.ExeID == selectedID)
                    {
                        List<tara_wcf.gamePlay> patientGamePlayList = new List<tara_wcf.gamePlay>();
                        patientGamePlayList = patientSession.GamePlaylist;

                        if (jointAvailable.Count == 0)
                        {

                            foreach (tara_wcf.gamePlay gameplay in patientGamePlayList)
                            {
                                jointAvailable.Add(gameplay.JointID);
                            }

                            jointAvailable = jointAvailable.Distinct().ToList();
                        }

                        List<KeyValuePair<KeyValuePair<int, string>, LineSeries>> jointChartLineList = new List<KeyValuePair<KeyValuePair<int, string>, LineSeries>>();
                        List<KeyValuePair<int, string>> jointLSuidList = new List<KeyValuePair<int, string>>();
                        foreach (int jointID in jointAvailable)
                        {
                            foreach (tara_wcf.gamePlay gameplay in patientGamePlayList)
                            {
                                foreach (string xyz in selectedXYZ)
                                {
                                    if (gameplay.GameKey.Contains(xyz) && gameplay.JointID == jointID)
                                    {
                                        if (gameValue1 == 0.0)
                                        {
                                            try
                                            {
                                                gameValue1 = Convert.ToDouble(gameplay.GameValue);
                                                xx[0] = patientSession.Dateofplay;
                                                yy[0] = gameValue1;
                                                temp.Add(new DataPoint<DateTime, double>() { X = xx[0], Y = yy[0] });
                                            }
                                            catch (Exception) { }

                                        }
                                        else
                                        {
                                            try
                                            {
                                                gameValue2 = Convert.ToDouble(gameplay.GameValue);
                                                xx[1] = patientSession.Dateofplay;
                                                yy[1] = gameValue2;
                                                temp.Add(new DataPoint<DateTime, double>() { X = xx[1], Y = yy[1] });
                                                LineSeries ls = new LineSeries();
                                                ls.DataSeries = temp;
                                                KeyValuePair<int, string> jointxyz = new KeyValuePair<int, string>(jointID, xyz);
                                                jointLSuidList.Add(jointxyz);
                                                jointChartLineList.Add(new KeyValuePair<KeyValuePair<int, string>, LineSeries>(jointxyz, ls));
                                                gameValue1 = 0.0;
                                                gameValue2 = 0.0;
                                            }
                                            catch (Exception) { }

                                        }
                                    }

                                }
                            } // end of gameplaylist
                            //if (gameplay.GameKey.Contains("Angle") && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                            //{

                        } //end of patientGamePlayList

                        //LineSeries ls = new LineSeries();

                        //SolidColorBrush color1 = new SolidColorBrush();
                        //color1.Color = Colors.Red;
                        //ls.LineStroke = color1;
                        //colorCount++;
                        //ls.LineStrokeThickness = 4;
                        //ls.DataSeries = temp;
                        //if (showLegendRange == false)
                        //{
                        //    showLegendRange = true;
                        //}
                        //else
                        //    ls.IsDisplayedOnLegend = false;
                        //progressChart.Series.Add(ls);

                        if (jointColorAssignList.Count == 0)
                        {

                            foreach (KeyValuePair<int, string> jointLSuid in jointLSuidList)
                            {
                                jointColorAssignList.Add(new KeyValuePair<KeyValuePair<int, string>, Color>(jointLSuid, colurList[colorCount]));
                                colorCount++;
                            }
                        }
                        foreach (KeyValuePair<KeyValuePair<int, string>, LineSeries> jointLSuid in jointChartLineList)
                        {
                            foreach (KeyValuePair<KeyValuePair<int, string>, Color> jointLSuidColor in jointColorAssignList)
                            {
                                if (jointLSuid.Key.Key == jointLSuidColor.Key.Key && jointLSuid.Key.Value == jointLSuidColor.Key.Value)
                                {
                                    LineSeries lineSeries = jointLSuid.Value;
                                    SolidColorBrush color1 = new SolidColorBrush();
                                    color1.Color = jointLSuidColor.Value;
                                    lineSeries.LineStrokeThickness = 4;
                                    lineSeries.IsDisplayedOnLegend = false;
                                    progressChart.Series.Add(lineSeries);
                                }
                            }
                        }

                    } // end of patientSession.ExeID
                } //end of patient session


                //DataSeries<DateTime, double> benchMax = new DataSeries<DateTime, double>("Max Benchmark");
                //benchMax.Add(new DataPoint<DateTime, double>() { X = xx[0], Y = 175 });
                //benchMax.Add(new DataPoint<DateTime, double>() { X = xx[1], Y = 175 });
                //LineSeries ls3 = new LineSeries();

                //SolidColorBrush color12 = new SolidColorBrush();
                //color12.Color = Colors.Black;
                //ls3.LineStroke = color12;
                //colorCount++;
                //ls3.LineStrokeThickness = 4;
                //ls3.DataSeries = benchMax;
                //progressChart.Series.Add(ls3);

                //DataSeries<DateTime, double> bench = new DataSeries<DateTime, double>("Min Benchmark");
                //bench.Add(new DataPoint<DateTime, double>() { X = xx[0], Y = 2 });
                //bench.Add(new DataPoint<DateTime, double>() { X = xx[1], Y = 2 });
                //LineSeries ls4 = new LineSeries();

                //SolidColorBrush color124 = new SolidColorBrush();
                //color124.Color = Colors.Black;
                //ls4.LineStroke = color124;
                //colorCount++;
                //ls4.LineStrokeThickness = 4;
                //ls4.DataSeries = bench;
                //progressChart.Series.Add(ls4);

                #endregion
            } // end of else loop


        }

        private void btnShow_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
        }

        #endregion

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            svc.retrieveAllEXEAsync();

            svc.retrieveAllTreatmentAsync();

            svc.retrieveAllAssessmentAsync();
            svc.getMaxMinAngleAsync(patientID);

            svc.retrieveSessionOfPatientAsync(patientID);
            svc.retrieveGameAssignedtoPatientAsync(patientID);
        }

        private void tbxSearchTreatment_GotFocus(object sender, RoutedEventArgs e)
        {
            if (tbxSearchTreatment.Text.Trim().ToString() == "Enter a search item")
            {
                tbxSearchTreatment.Text = "";
            }
        }

        private void tbxSearchTreatment_LostFocus(object sender, RoutedEventArgs e)
        {
            if (tbxSearchTreatment.Text.Trim().ToString() == "")
            {
                tbxSearchTreatment.Text = "Enter a search item";
            }
        }

        void svc_searchAssessmentCompleted(object sender, tara_wcf.searchAssessmentCompletedEventArgs e)
        {
            if (e.Error == null && e.Result != null)
            {
                treatmentPanel.Children.Clear();
                foreach (tara_wcf.EXE x in e.Result)
                {
                    treatmentPanel.Children.Add(new TreatmentItem(x));
                }
            }
        }

        private void btnSearchTreatment_Click(object sender, RoutedEventArgs e)
        {
            if (tbxSearchTreatment.Text.Trim().Length != 0)
            {
                treatmentPanel.Children.Clear();
                foreach (tara_wcf.EXE y in exeList)
                {
                    if (y.Name.ToUpper().Contains(tbxSearchTreatment.Text.ToUpper()))
                    {
                        treatmentPanel.Children.Add(new TreatmentItem(y));
                    }
                }
            }
        }

        private void tbxSearchTreatment_KeyDown(object sender, KeyEventArgs e)
        {
            if (tbxSearchTreatment.Text.Trim().Length != 0)
            {
                if (e.Key == Key.Enter)
                {
                    treatmentPanel.Children.Clear();
                    foreach (tara_wcf.EXE y in exeList)
                    {
                        if (y.Name.ToUpper().Contains(tbxSearchTreatment.Text.ToUpper()))
                        {
                            treatmentPanel.Children.Add(new TreatmentItem(y));
                        }
                    }
                }
            }
        }

        private void btnAll_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            treatmentPanel.Children.Clear();
            foreach (tara_wcf.EXE x in exeList)
            {
                treatmentPanel.Children.Add(new TreatmentItem(x));
            }
        }
	}
}